﻿using AutoMapper;
using IntelligentAgriculture.Contracts.Dto.Input;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.WebAPI.Application.Command.VendorModelCommand;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;

namespace IntelligentAgriculture.WebAPI.Application.CommandHandler.VendorModelCommandHandler
{
	/// <summary>
	/// 应用商采购
	/// </summary>
	public class ImportCustomerCommandHandler : IRequestHandler<ImportCustomerCommand, Results<bool>>
	{
		private readonly IVendorModelService _vendorModelService;
		private readonly IMapper _mapper;
		/// <summary>
		/// 构造方法
		/// </summary>
		/// <param name="vendorModelService"></param>
		public ImportCustomerCommandHandler(IVendorModelService vendorModelService, IMapper mapper)
		{
			_vendorModelService = vendorModelService;
			_mapper = mapper;
		}
		public async Task<Results<bool>> Handle(ImportCustomerCommand request, CancellationToken cancellationToken)
		{
			// 读取文件内容
			MemoryStream memoryStream = new MemoryStream();
			//将传进来的文件拷贝到内存流中
			request.File.CopyTo(memoryStream);
			//通过内存流读取文件内容
			var list = await memoryStream.QueryAsync<VendorModelminiExcelInPut>();

			// 转换为实体
			var costomer = _mapper.Map<List<VendorModelminiExcelInPut>, List<Vendormodel>>(list.ToList());
			foreach (var item in costomer)
			{
				//批量添加
				await _vendorModelService.AddVendormodels(item);
			}
			 new OkObjectResult("导入成功");
			return new Results<bool> { Code = 200, Data = true };
		}
	}
}
